﻿using UnityEngine;
using System.Collections;

public class U3dSingletonAuto<T> : MonoBehaviour where T : MonoBehaviour
{
	protected static T _instance = default(T);
	static readonly object syncLock = new object();

	void OnApplicationQuit () {
		_instance = null;
		if (null != gameObject) {
			DestroyObject (gameObject);
		}
	}

	public static T Instance {
		get {
			lock (syncLock) {
				if (_instance == null) {
				    T[] trush = FindObjectsOfType(typeof(T)) as T[];
				    if(trush.Length > 1)
				    {
					    foreach(T t in trush)
					    {
						    DestroyImmediate(t.gameObject);
					    }
				    }

					_instance = FindObjectOfType(typeof(T)) as T;
					
					if ( FindObjectsOfType(typeof(T)).Length > 1 ) {
                        ETModel.Log.Error("[Singleton] Something went really wrong " +
						               " - there should never be more than 1 singleton!" +
						               " Reopenning the scene might fix it.");
						return _instance;
					}
					
					if (_instance == null) {
						GameObject singleton = new GameObject();
						singleton.name = string.Format ("Singleton({0})<Auto>", typeof(T));
                        //singleton.transform.parent = Globals.AutoSingletonRoot.transform;
						singleton.transform.localPosition = Vector3.zero;

						_instance = singleton.AddComponent<T>();
						
						// DontDestroyOnLoad(singleton);
					} else {
                        ETModel.Log.Warning("[Singleton] Using instance already created: " +
						          _instance.gameObject.name);
					}
				}
				
				return _instance;
			} // End lock (syncLock)
		}
	}
}
